import { useCrudForm } from "@/composables/useCrudForm";
import { leaveFormConfig } from "../form-config";
import { formatDateTime } from "@/utils/xenUtils";
import SysDailyLeaveRequestBillApi from "../api/index";
import commonApi from "@/api/common";
import type {
  ISysDailyLeaveRequestBill,
  ISysDailyLeaveRequestBillVm,
} from "../api/interface";

/**
 * 请假出差申请单信息专用 Composable
 */
export function useLeaveInfo() {
  // 创建API实例
  const api = SysDailyLeaveRequestBillApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
    // 单据编号接口 - 适配器处理类型差异
    getBillCode: async () => {
      const result = await api.getBillCode();
      return { Data: result.Data || "" };
    },
  };

  // 选项数据加载器
  const optionLoaders = {
    groupId: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    personId: async () => {
      // 返回空数组，人员选择通过自动补全搜索实现
      return [];
    },
  };

  /**
   * 获取当前登录用户信息
   */
  const getCurrentUserInfo = () => {
    return uni.getStorageSync("userInfo");
  };

  /**
   * 根据工号搜索员工信息并自动填充
   */
  const searchEmployeeByStaffNo = async (staffNo: string) => {
    if (!staffNo) return null;

    try {
      // 使用工号搜索员工
      const searchParams = {
        PageIndex: 1,
        State: '在职', // 只搜索在职员工
        StaffNo: staffNo
      };

      const response = await api.searchPersons(searchParams);

      // 检查响应是否成功
      if (response.Code !== 200 || !response.Data || response.Data.length === 0) {
        console.warn('根据工号搜索员工失败:', response.Msg || '未找到员工信息');
        return null;
      }

      // 返回第一个匹配的员工信息
      const person = response.Data[0];
      return {
        value: person.ID,
        text: person.Name,
        subtitle: `工号: ${person.StaffNo}${person.GroupName ? ` | ${person.GroupName}` : ''}`,
        extData: {
          staffNo: person.StaffNo,
          orgId: person.OrgId || person.Org?.ID,
          orgName: person.OrgName || person.Org?.Name,
          groupId: person.GroupId || person.Group?.ID,
          groupName: person.GroupName || person.Group?.GroupName,
        }
      };
    } catch (error) {
      console.error('搜索员工信息异常:', error);
      return null;
    }
  };

  /**
   * 自动填充当前用户的员工信息
   */
  const autoFillCurrentUserEmployee = async () => {
    const userInfo = getCurrentUserInfo();
    if (!userInfo || !userInfo.ITCode) {
      console.warn('无法获取当前用户信息或工号');
      return false;
    }

    // 根据当前用户的工号搜索员工信息
    const employeeInfo = await searchEmployeeByStaffNo(userInfo.ITCode);
    if (!employeeInfo) {
      console.warn('未找到当前用户对应的员工信息');
      return false;
    }

    // 自动填充表单数据
    crudForm.formData.personId = employeeInfo.text; // 显示员工姓名
    crudForm.pickerValues.personId = employeeInfo.value; // 存储员工ID

    // 填充员工工号、姓名、公司和部门信息
    if (employeeInfo.extData) {
      crudForm.formData.staffNo = employeeInfo.extData.staffNo || "";
      crudForm.formData.name = employeeInfo.text;
      crudForm.formData.orgName = employeeInfo.extData.orgName || "";
      crudForm.formData.groupName = employeeInfo.extData.groupName || "";

      // 更新选择器值
      crudForm.pickerValues.orgId = employeeInfo.extData.orgId || "";
      crudForm.pickerValues.groupId = employeeInfo.extData.groupId || "";

      // 同步到表单数据中的隐藏字段
      crudForm.formData.orgId = employeeInfo.extData.orgId || "";
      crudForm.formData.groupId = employeeInfo.extData.groupId || "";
    }

    console.log('自动填充员工信息成功:', employeeInfo);
    return true;
  };

  /**
   * 搜索员工（自动补全用）
   */
  const searchEmployees = async (query: string) => {
    // 判断输入的是工号还是姓名
    // 如果输入的是纯数字，则按工号搜索；否则按姓名搜索
    const isStaffNo = /^\d+$/.test(query.trim());

    // 根据输入类型构建搜索参数
    const searchParams: any = {
      PageIndex: 1,
      State: '在职' // 只搜索在职员工
    };

    // 根据输入类型设置搜索字段
    if (isStaffNo) {
      searchParams.StaffNo = query;
    } else {
      searchParams.Name = query;
    }

    // 使用新的员工搜索API
    const response = await api.searchPersons(searchParams);

    // 检查响应是否成功
    if (response.Code !== 200 || !response.Data) {
      console.warn('员工搜索API返回异常:', response.Msg || '未知错误');
      return [];
    }

    // 转换为自动补全组件期望的格式
    return response.Data.map((person: any) => ({
      value: person.ID,
      text: person.Name,
      subtitle: `工号: ${person.StaffNo}${person.GroupName ? ` | ${person.GroupName}` : ''}`, // 显示工号和部门作为副标题
      // 扩展数据，包含公司和部门信息
      extData: {
        staffNo: person.StaffNo,
        orgId: person.OrgId || person.Org?.ID,
        orgName: person.OrgName || person.Org?.Name,
        groupId: person.GroupId || person.Group?.ID,
        groupName: person.GroupName || person.Group?.GroupName,
      }
    }));
  };

  // 为personId字段配置searchApi
  if (leaveFormConfig.personId) {
    leaveFormConfig.personId.searchApi = searchEmployees;
  }

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysDailyLeaveRequestBill, ISysDailyLeaveRequestBillVm>(
    leaveFormConfig,
    apiConfig,
    optionLoaders
  );

  // 初始化新字段的默认值
  if (!crudForm.formData.orgId) {
    crudForm.formData.orgId = "";
  }
  if (!crudForm.formData.orgName) {
    crudForm.formData.orgName = "";
  }
  if (!crudForm.formData.groupName) {
    crudForm.formData.groupName = "";
  }

  /**
   * 计算天数
   */
  const calculateDays = (startTime: string, endTime: string): string => {
    if (!startTime || !endTime) return "";

    const start = new Date(startTime);
    const end = new Date(endTime);

    if (start > end) return "0";

    // 计算天数差（包含结束日期）
    const timeDiff = end.getTime() - start.getTime();
    const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;

    return daysDiff.toString();
  };

  // 监听开始时间和结束时间变化，自动计算天数
  const handleDateChange = () => {
    const startTime = crudForm.formData.startTime;
    const endTime = crudForm.formData.endTime;

    if (startTime && endTime) {
      crudForm.formData.days = calculateDays(startTime, endTime);
    } else {
      crudForm.formData.days = "";
    }
  };

  // 监听表单数据变化，自动计算天数
  const watchFormDataForDays = () => {
    handleDateChange();
  };

  /**
   * 转换表单数据为API格式（新增）
   */
  const convertFormDataToApiFormatForCreate = (): ISysDailyLeaveRequestBillVm => {
    return {
      Entity: {
        PersonId: crudForm.pickerValues.personId || null,
        StaffNo: crudForm.formData.staffNo || null,
        Name: crudForm.formData.name || null,
        LeaveType: crudForm.formData.leaveType || null,
        StartTime: crudForm.formData.startTime ? new Date(crudForm.formData.startTime) : null,
        EndTime: crudForm.formData.endTime ? new Date(crudForm.formData.endTime) : null,
        Days: crudForm.formData.days || null,
        Reason: crudForm.formData.reason || null,
        Approver: null,
        ApprovalTime: null,
        // 公司ID和部门ID信息
        OrgId: crudForm.pickerValues.orgId || crudForm.formData.orgId || null,
        GroupId: crudForm.pickerValues.groupId || crudForm.formData.groupId || null,
        BillCode: crudForm.formData.billCode || null,
        // BillStatus和WorkflowStatus不传值，由系统自动设置
        BillStatus: null,
        WorkflowStatus: null,
        Remark: crudForm.formData.remark || null,
      },
      ActionName: null,
      IsMyApprove: null,
    };
  };

  /**
   * 转换表单数据为API格式（编辑）
   */
  const convertFormDataToApiFormatForEdit = (): ISysDailyLeaveRequestBillVm => {
    const originalData = crudForm.originalData.value;
    if (!originalData) {
      throw new Error("原始数据不存在");
    }

    return {
      Entity: {
        ID: originalData.ID || null,
        PersonId: crudForm.pickerValues.personId || originalData.PersonId,
        StaffNo: crudForm.formData.staffNo || originalData.StaffNo,
        Name: crudForm.formData.name || originalData.Name,
        LeaveType: crudForm.formData.leaveType || originalData.LeaveType,
        StartTime: crudForm.formData.startTime ? new Date(crudForm.formData.startTime) : originalData.StartTime,
        EndTime: crudForm.formData.endTime ? new Date(crudForm.formData.endTime) : originalData.EndTime,
        Days: crudForm.formData.days || originalData.Days,
        Reason: crudForm.formData.reason || originalData.Reason,
        Approver: originalData.Approver,
        ApprovalTime: originalData.ApprovalTime,
        // 公司ID和部门ID信息
        OrgId: crudForm.pickerValues.orgId || crudForm.formData.orgId || originalData.OrgId,
        GroupId: crudForm.pickerValues.groupId || crudForm.formData.groupId || originalData.GroupId,
        BillCode: crudForm.formData.billCode || originalData.BillCode,
        // BillStatus和WorkflowStatus不传值，由系统自动设置
        BillStatus: '草稿',
        WorkflowStatus: '提交中',
        Remark: crudForm.formData.remark || originalData.Remark,
      },
      ActionName: null,
      IsMyApprove: null,
    };
  };

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",

    // 基本信息
    personId: "PersonId",
    staffNo: "StaffNo",
    name: "Name",
    orgId: "OrgId", // 原始的公司ID字段
    orgName: "Org.Name", // 公司名称字段，通过processedData处理
    groupName: "Group.GroupName", // 部门名称字段，通过processedData处理

    // 请假出差信息
    leaveType: "LeaveType",
    startTime: "StartTime",
    endTime: "EndTime",
    days: "Days",
    reason: "Reason",

    // 工作信息
    groupId: "GroupId",

    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",

    remark: "Remark",
  };

  /**
   * 加载请假出差申请单详情数据
   */
  const loadLeaveDetail = async (id: string): Promise<{ success: boolean; isMyApprove?: boolean }> => {
    // 直接调用API获取完整响应
    const response = await api.get(id);

    if (response && response.Entity) {
      const detail = response.Entity;

      // 设置原始数据
      crudForm.originalData.value = detail;

      // 检查原始数据中的日期字段
      const dateFields = ["ApprovalTime", "StartTime", "EndTime"];
      dateFields.forEach(field => {
        if ((detail as any)[field]) {
          console.log(`原始数据中的日期字段 ${field}:`, (detail as any)[field]);
        }
      });

      // 先使用通用转换
      crudForm.convertApiDataToFormData(detail, fieldMapping);

      // 添加特殊处理，确保选择器字段正确映射
      await ensurePickerFieldsMapping(detail);

      return {
        success: true,
        isMyApprove: response.IsMyApprove || false
      };
    }
    return { success: false };
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理单据编号
    if (apiData.BillCode) {
      crudForm.formData.billCode = apiData.BillCode;
    }

    // 处理单据状态
    if (apiData.BillStatus !== undefined) {
      const statusText = apiData.BillStatus === "草稿" ? "草稿" : "正文";
      crudForm.formData.billStatus = statusText;
      crudForm.pickerValues.billStatus = apiData.BillStatus.toString();
    }

    // 处理工作流状态显示
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理请假类型
    if (apiData.LeaveType !== undefined) {
      // 直接使用字符串值
      crudForm.formData.leaveType = apiData.LeaveType;
    }

    // 处理公司ID
    if (apiData.OrgId) {
      crudForm.formData.orgId = apiData.OrgId;
      crudForm.pickerValues.orgId = apiData.OrgId;
    }

    // 处理所属部门
    if (apiData.GroupId) {
      // 对于department-picker类型，formData中存储部门ID（用于组件显示选中状态）
      crudForm.formData.groupId = apiData.GroupId;
      crudForm.pickerValues.groupId = apiData.GroupId;
    }

    // 处理员工信息
    console.log("处理员工信息，apiData.Name:", apiData.Name, "apiData.PersonId:", apiData.PersonId);

    // 始终从API数据设置员工姓名，确保有值显示
    if (apiData.Name) {
      // 设置autocomplete组件显示的文本（编辑页显示员工姓名）
      crudForm.formData.personId = apiData.Name;
      console.log("设置员工姓名显示:", apiData.Name);
    }

    // 设置实际的员工ID用于提交
    if (apiData.PersonId) {
      crudForm.pickerValues.personId = apiData.PersonId;
      console.log("设置员工ID:", apiData.PersonId);
    }

    // 如果有选项数据，也尝试匹配设置
    if (apiData.PersonId && leaveFormConfig.personId?.optionsData) {
      const personOption = leaveFormConfig.personId.optionsData.find(
        (option: any) => option.value === apiData.PersonId
      );
      if (personOption) {
        crudForm.formData.personId = personOption.text;
        crudForm.pickerValues.personId = apiData.PersonId;
        console.log("从选项数据匹配设置员工信息:", personOption.text);
      }
    }

    // 处理员工工号和姓名（从API数据直接获取）
    if (apiData.StaffNo) {
      crudForm.formData.staffNo = apiData.StaffNo;
    }
    if (apiData.Name) {
      crudForm.formData.name = apiData.Name;
    }

    // 处理审批时间格式化
    if (apiData.ApprovalTime) {
      crudForm.formData.approvalTime = formatDateTime(apiData.ApprovalTime);
    }

    // 处理开始时间格式化
    if (apiData.StartTime) {
      const formattedDateTime = formatDateTime(apiData.StartTime);
      crudForm.formData.startTime = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
    }

    // 处理结束时间格式化
    if (apiData.EndTime) {
      const formattedDateTime = formatDateTime(apiData.EndTime);
      crudForm.formData.endTime = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
    }

    // 处理天数
    if (apiData.Days) {
      crudForm.formData.days = apiData.Days.toString();
    }

    // 处理工作流状态
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理审批人
    if (apiData.Approver) {
      crudForm.formData.approver = apiData.Approver;
    }
  };

  /**
   * 创建请假出差申请单（两步提交流程）
   * 第一步：调用Add接口保存草稿
   * 第二步：调用Edit接口提交
   */
  const createLeave = async (): Promise<{
    success: boolean;
    data?: ISysDailyLeaveRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 第一步：调用Add接口保存草稿
    const apiData = convertFormDataToApiFormatForCreate();
    const addResult = await crudForm.create(apiData);

    if (!addResult || !addResult.ID) {
      return {
        success: false,
        validation: validationResult,
        error: "保存草稿失败，请重试"
      };
    }

    // 第二步：调用Edit接口进行提交
    // 设置原始数据为第一步返回的结果，用于Edit接口
    crudForm.originalData.value = addResult;

    // 创建编辑数据格式进行提交
    const editApiData = convertFormDataToApiFormatForEdit();

    const editResult = await crudForm.update(editApiData);

    if (!editResult) {
      return {
        success: false,
        validation: validationResult,
        error: "提交失败，数据已保存为草稿，请稍后重试"
      };
    }

    return {
      success: true,
      data: editResult,
      validation: validationResult
    };
  };

  /**
   * 保存请假出差申请单（编辑）
   */
  const saveLeave = async (): Promise<{
    success: boolean;
    data?: ISysDailyLeaveRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 验证关键数据
    if (!crudForm.originalData.value) {
      return {
        success: false,
        error: "原始数据丢失，请重新加载页面",
        validation: validationResult
      };
    }

    const apiData = convertFormDataToApiFormatForEdit();
    const result = await crudForm.update(apiData);

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  /**
   * 更新表单配置中的部门数据
   */
  const updateDepartmentData = async () => {
    const commonApiInstance = commonApi();
    const departmentData = await commonApiInstance.GetParentsTree();

    // 更新表单配置中的部门数据
    if (leaveFormConfig.groupId && departmentData) {
      leaveFormConfig.groupId.departmentData = departmentData;
      // 同时设置optionsData，用于数据映射
      leaveFormConfig.groupId.optionsData = departmentData.map((item: any) => ({
        value: item.Value,
        text: item.Text,
      }));
    }

    return departmentData;
  };

  /**
   * 重写 initializeOptions 方法，同时更新部门数据
   */
  const initializeOptions = async (): Promise<boolean> => {
    // 先调用原始的 initializeOptions
    const result = await crudForm.initializeOptions();

    // 然后更新部门数据
    await updateDepartmentData();

    return result;
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 重写 initializeOptions 方法
    initializeOptions,

    // 请假出差申请单信息专用方法
    loadLeaveDetail,
    createLeave,
    saveLeave,
    updateDepartmentData,
    searchEmployees,
    calculateDays,
    handleDateChange,
    watchFormDataForDays,

    // 用户信息相关方法
    getCurrentUserInfo,
    searchEmployeeByStaffNo,
    autoFillCurrentUserEmployee,

    // API数据转换方法
    convertFormDataToApiFormatForCreate,
    convertFormDataToApiFormatForEdit,

    // 字段映射
    fieldMapping,
  };
}
